package mx.netbrain.dao.impl;

import java.util.List;

import mx.netbrain.dao.PropertiesRepositoriesDao;
import mx.netbrain.model.PropertiesRepositories;
import mx.netbrain.model.PropertiesRepositoriesValue;
import mx.netbrain.model.Repositories;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

public class PropertiesRepositoriesDaoImpl implements PropertiesRepositoriesDao {

	private static final Logger logger = Logger
			.getLogger(PropertiesRepositoriesDaoImpl.class);

	@Override
	public void save(PropertiesRepositories propertiesRepositories) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(propertiesRepositories);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PropertiesRepositories> listForRepositories(
			Repositories repositories) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String sql = "select propertiesrepositories from PropertiesRepositories as propertiesrepositories"
				+ " where propertiesrepositories.repositories.id = :repositories";
		Query query = session.createQuery(sql);
		query.setLong("repositories", repositories.getId());
		return query.list();
	}

	@Override
	public void saveValue(PropertiesRepositoriesValue values) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.saveOrUpdate(values);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public PropertiesRepositoriesValue findPropertieValue(Long repo, Long tree,
			Long properties) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String sql = "select propertiesrepositoriesvalue "
				+ "from PropertiesRepositoriesValue as propertiesrepositoriesvalue where "
				+ "propertiesrepositoriesvalue.id.repository = :repo and "
				+ "propertiesrepositoriesvalue.id.tree = :tree and "
				+ "propertiesrepositoriesvalue.propertiesRepositories = :props";
		Query query = session.createQuery(sql);
		query.setLong("repo", repo);
		query.setLong("tree", tree);
		query.setLong("props", properties);
		return (PropertiesRepositoriesValue) query.uniqueResult();
	}

}
